/*
* ========== Copyright Header Begin ==========================================
* 
* OpenSPARC T1 Processor File: allocate.c
* Copyright (c) 2006 Sun Microsystems, Inc.  All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
* 
* The above named program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2 as published by the Free Software Foundation.
* 
* The above named program is distributed in the hope that it will be 
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* General Public License for more details.
* 
* You should have received a copy of the GNU General Public
* License along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
* 
* ========== Copyright Header End ============================================
*/
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"@(#)allocate.c	1.5	06/04/26 SMI"

#include <string.h>
#include <malloc.h>
#include <unistd.h>
#include <stdlib.h>

#include "basics.h"
#include "fatal.h"
#include "allocate.h"


	/*
	 * Simple allocation routines
	 */



void * xmalloc(int size, int linen, char * filen)
{
	void *p;

	if (size<=0) {
		if (size<0) fatal("xmalloc of negative size (%d) at %d in %s",
			linen, filen);
		warning("xmalloc of zero size at %d in %s", linen, filen);
		return (void*)0;
	}

	p = malloc(size);
	if (p == (void*)0) fatal("malloc of %d at %d in %s", size, linen, filen);

	return p;
}


void * xcalloc(int num, int size, int linen, char * filen)
{
	void *p;

	if (size<=0 || num<=0)
		fatal("xcalloc(%d,%d) : one of number or size is <= 0 at line %d of %s",
			num, size, linen, filen);

	p = calloc(num, size);
	if (p == (void*)0) fatal("calloc of %d of size %d at %d in %s", num, size, linen, filen);

	return p;
}



void xfree(void * p, int linen, char * filen)
{
	if (p == (void*)0) {
		warning("xfree of null pointer at %d in %s", linen, filen);
		return;
	}

	free(p);
}


void * xrealloc(void * oldp, int size, int linen, char * filen)
{
	void *p;

	if (size <= 0) {
		if (size == 0) {
			xfree(oldp, linen, filen);
			warning("xrealloc to zero size at %d in %s", linen, filen);
			return (void*)0;
		}

		fatal("xrealloc to negative size %d at %d in %s", size, linen, filen);
	}

	if (oldp == (void*)0) {
		p = malloc(size);
	} else {
		p = realloc(oldp, size);
	}

	if (p == (void*)0) fatal("xrealloc failed @ %d in %s", linen, filen);

	return p;
}



char * xstrdup(char * strp, int linen, char * filen)
{
	char * p;

	p = strdup(strp);
	if (p == (char*)0) fatal("xstrdup @ %d in %s failed", linen, filen);

	return p;
}

